import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import DefaultLayout from '@/layouts/Default.vue'
import staticRoutes from './static'
import { generateRoutesFromMenus } from './dynamic'
import { useUserStore } from '@/stores/user'

const router = createRouter({
    history: createWebHashHistory(import.meta.env.VITE_BASE_URL),
    routes: [...staticRoutes]
})

/**
 * 动态添加路由
 * @returns Promise<void>
 */
const addDynamicRoutes = async (): Promise<void> => {
    const userStore = useUserStore()
    // 获取用户的菜单列表
    if (userStore.menus && userStore.menus.length > 0) {
        const dynamicRoutes: RouteRecordRaw[] = generateRoutesFromMenus(userStore.menus)
        dynamicRoutes.forEach((route) => {
            router.addRoute(route)
        })
    }
}

//路由守卫
router.beforeEach(async (to, from) => {
    const userStore = useUserStore()
    const token = localStorage.getItem('token')
    if (to.path !== '/login' && !token) {
        return { name: 'login' }
    }
    if (!userStore.hasDynamicRoutes && import.meta.env.VITE_ROUTE_MODE === 'dynamic' && to.path !== '/login') {
        await addDynamicRoutes()
        userStore.hasDynamicRoutes = true
        return to.fullPath
    }
})

export default router
